package com.info33.platform.common.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 如果JDK版本是1.8,可使用原生Base64类
 *
 * @author Administrator
 */
@Slf4j
@SuppressWarnings("SpellCheckingInspection")
public class SendSms {

    /**
     * 无需修改,用于格式化鉴权头域,给"X-WSSE"参数赋值
     */
    private static final String WSSE_HEADER_FORMAT = "UsernameToken Username=\"%s\",PasswordDigest=\"%s\",Nonce=\"%s\",Created=\"%s\"";
    /**
     * 无需修改,用于格式化鉴权头域,给"Authorization"参数赋值
     */
    private static final String AUTH_HEADER_VALUE = "WSSE realm=\"SDP\",profile=\"UsernameToken\",type=\"Appkey\"";

    private SendSms() {
    }

    /**
     * 发送验证码
     *
     * @param mobile 手机号
     * @param code   验证码
     * @throws Exception exception
     */
    public static void sendCode(String mobile, Integer code) throws Exception {
        sendMessage(
                "8822051025671",
                "a4368d7bf3bd4ea6ada78425f82de5c3",
                null,
                "+86" + mobile,
                "[\"" + code + "\"]",
                null);
    }

    /**
     * 发送短信
     *
     * @param sender         模板ID 国内短信签名通道号或国际/港澳台短信通道号 String sender = "csms12345678"; //国内短信签名通道号或国际/港澳台短信通道号
     * @param templateId     模板ID
     * @param signature      条件必填,国内短信关注,当templateId指定的模板类型为通用模板时生效且必填,必须是已审核通过的,与模板类型一致的签名名称 国际/港澳台短信不用关注该参数 String signature = "华为云短信测试"; //签名名称
     * @param receiver       必填,全局号码格式(包含国家码),示例:+8615123456789,多个号码之间用英文逗号分隔 例如：String receiver = "+8615123456789,+8615234567890"; //短信接收人号码
     * @param templateParas  选填,使用无变量模板时请赋空值 String templateParas = "";
     *                       单变量模板示例:模板内容为"您的验证码是${1}"时,templateParas可填写为"[\"369751\"]"
     *                       双变量模板示例:模板内容为"您有${1}件快递请到${2}领取"时,templateParas可填写为"[\"3\",\"人民公园正门\"]"
     *                       模板中的每个变量都必须赋值，且取值不能为空
     *                       查看更多模板和变量规范:产品介绍>模板和变量规范
     *                       例如：String templateParas = "[\"369751\"]"; //模板变量，此处以单变量验证码短信为例，请客户自行生成6位验证码，并定义为字符串类型，以杜绝首位0丢失的问题（例如：002569变成了2569）。
     * @param statusCallBack 选填,短信状态报告接收地址,推荐使用域名,为空或者不填表示不接收状态报告
     * @throws Exception -
     */
    public static void sendMessage(String sender, String templateId, String signature, String receiver, String templateParas, String statusCallBack) throws Exception {
        // 必填,请参考"开发准备"获取如下数据,替换为实际值
        // APP接入地址+接口访问URI
        String url = "https://rtcsms.cn-north-1.myhuaweicloud.com:10743/sms/batchSendSms/v1";
        // APP_Key
        String appKey = "KK5GfiF5A9T70bM68Z335EbX7KCA";
        // APP_Secret
        String appSecret = "MNPhlJtW2IHaik80hc3I7HHERsg9";

        // 请求Body,不携带签名名称时,signature请填null
        String body = buildRequestBody(sender, receiver, templateId, templateParas, statusCallBack, signature);
        if (null == body || body.isEmpty()) {
            log.warn("body is null.");
            return;
        }

        //请求Headers中的X-WSSE参数值
        String wsseHeader = buildWsseHeader(appKey, appSecret);
        if (null == wsseHeader || wsseHeader.isEmpty()) {
            log.warn("wsse header is null.");
            return;
        }
        //如果JDK版本是1.8,可使用如下代码
        //为防止因HTTPS证书认证失败造成API调用失败,需要先忽略证书信任问题
        CloseableHttpClient client = HttpClients.custom()
                .setSSLContext(new SSLContextBuilder().loadTrustMaterial(null,
                        (x509CertChain, authType) -> true).build())
                .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                .build();
        // 请求方法POST
        HttpResponse response = client.execute(RequestBuilder.create("POST")
                .setUri(url)
                .addHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded")
                .addHeader(HttpHeaders.AUTHORIZATION, AUTH_HEADER_VALUE)
                .addHeader("X-WSSE", wsseHeader)
                .setEntity(new StringEntity(body)).build());
        // 打印响应头域信息
        log.info(response.toString());
        // 打印响应消息实体
        log.info(EntityUtils.toString(response.getEntity()));
    }

    /**
     * 构造请求Body体
     *
     * @param sender-
     * @param receiver-
     * @param templateId-
     * @param templateParas-
     * @param statusCallbackUrl-
     * @param signature          | 签名名称,使用国内短信通用模板时填写
     * @return -
     */
    static String buildRequestBody(String sender, String receiver, String templateId, String templateParas,
                                   String statusCallbackUrl, String signature) {
        if (null == sender || null == receiver || null == templateId || sender.isEmpty() || receiver.isEmpty()
                || templateId.isEmpty()) {
            log.warn("buildRequestBody(): sender, receiver or templateId is null.");
            return null;
        }
        List<NameValuePair> keyValues = new ArrayList<>();

        keyValues.add(new BasicNameValuePair("from", sender));
        keyValues.add(new BasicNameValuePair("to", receiver));
        keyValues.add(new BasicNameValuePair("templateId", templateId));
        if (null != templateParas && !templateParas.isEmpty()) {
            keyValues.add(new BasicNameValuePair("templateParas", templateParas));
        }
        if (null != statusCallbackUrl && !statusCallbackUrl.isEmpty()) {
            keyValues.add(new BasicNameValuePair("statusCallback", statusCallbackUrl));
        }
        if (null != signature && !signature.isEmpty()) {
            keyValues.add(new BasicNameValuePair("signature", signature));
        }

        return URLEncodedUtils.format(keyValues, StandardCharsets.UTF_8);
    }

    /**
     * 构造X-WSSE参数值
     *
     * @param appKey-
     * @param appSecret-
     * @return -
     */
    static String buildWsseHeader(String appKey, String appSecret) {
        if (null == appKey || null == appSecret || appKey.isEmpty() || appSecret.isEmpty()) {
            log.warn("buildWsseHeader(): appKey or appSecret is null.");
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        // Created
        String time = sdf.format(new Date());
        // Nonce
        String nonce = UUID.randomUUID().toString().replace("-", "");

        byte[] passwordDigest = DigestUtils.sha256(nonce + time + appSecret);
        String hexDigest = Hex.encodeHexString(passwordDigest);

        // 如果JDK版本是1.8,请加载原生Base64类,并使用如下代码
        // PasswordDigest
        String passwordDigestBase64Str = Base64.getEncoder().encodeToString(hexDigest.getBytes());

        return String.format(WSSE_HEADER_FORMAT, appKey, passwordDigestBase64Str, nonce, time);
    }

    /**
     * 解析上行短信通知数据
     *
     * @param data 短信平台推送的上行短信通知数据
     */
    public static Map<String, String> onSmsUpData(String data) {
        if (null == data || data.isEmpty()) {
            System.out.println("onSmsUpData(): data is null.");
            return Collections.emptyMap();
        }
        Map<String, String> keyValues = new HashMap<>(16);
        try {
            // 解析上行短信通知数据
            String[] params = URLDecoder.decode(data, "UTF-8").split("&");
            String[] temp;
            for (String param : params) {
                temp = param.split("=");
                if (temp.length == 2 && null != temp[1] && temp[1] != "") {
                    keyValues.put(temp[0], temp[1]);
                }
            }

            /*
             * Example: 此处已解析body为例,请按需解析所需参数并自行实现相关处理
             *
             * 'smsMsgId': 上行短信唯一标识
             * 'from': 上行短信发送方的号码
             * 'to': 上行短信接收方的号码
             * 'body': 上行短信发送的内容
             */

            // 上行短信发送的内容
            return keyValues;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return Collections.emptyMap();
    }
}
